package com.leyou.user.interceptors;

import com.leyou.common.auth.JwtUtils;
import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.entity.Payload;
import com.leyou.user.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author xiuer
 * @description 校验请求头中的token
 * @create 2019/7/11 16:19
 */
@Slf4j
public class PrivilegeInterceptor implements HandlerInterceptor {
     private JwtProperties properties;

     public PrivilegeInterceptor(JwtProperties properties) {
         this.properties = properties;
     }
    /*@Autowired
    private JwtProperties properties;*/

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            //获取jwT
            String headerName = properties.getPrivilege().getHeaderName();
            String token = request.getHeader(headerName);
            //解析jwt
            Payload<AppInfo> payload = JwtUtils.getInfoFromToken(token, properties.getPublicKey(), AppInfo.class);
            List<Long> targetList = payload.getUserInfo().getTargetList();
            //判断该jwt是否有访问自己的权限
            if (!targetList.contains(properties.getApp().getId())) {
                throw new RuntimeException("【用户微服务】，没有访问权限");
            }
            log.info("【用户微服务】，服务{}，正在访问路径{}", payload.getUserInfo().getServiceName(),
                    request.getRequestURI());
            return true;
        } catch (Exception e) {
            log.error("【用户微服务】访问出现异常 原因{}", e.getMessage());
            throw new RuntimeException("【用户微服务】出现异常", e);
        }

    }
}
